package com.qf.web;

import com.alibaba.fastjson.JSON;
import com.qf.web.common.R;
import com.qf.web.pojo.User;
import com.qf.web.service.UserService;
import com.qf.web.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();

        user.setUsername(username);
        user.setPassword(password);
        UserServiceImpl userService = new UserServiceImpl();

        User currentUser = userService.login(user);

        R<User> r = new R();
        if (currentUser != null) {
            //登录成功
            r.setCode(200);
            r.setMsg("登录成功");
            r.setData(currentUser);
            String s = JSON.toJSONString(r);
            resp.getWriter().println(s);
        } else {
            //登陆失败
            r.setCode(500);
            r.setMsg("登录失败");
            String s = JSON.toJSONString(r);
            resp.getWriter().println(s);
        }


    }
}
